﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KnowledgeEntity;
using System.Web.Security;

namespace MVC3Demo.Controllers
{
   public class ArticleController : Controller
   {
      //
      // GET: /Article/

      public ActionResult Index()
      {
         ViewData["rootCategory"] = KnowledgeEntity.Category.GetAllCategories()[-1];
         return View("EditArticle");
      }

      /// <summary>
      /// 申请进行条目编辑
      /// </summary>
      /// <param name="articleID"></param>
      /// <returns></returns>
      public ActionResult EditArticle(int? articleID)
      {
         if (!Request.IsAuthenticated)//如果当前用户未登录，则先登录再继续编辑操作
         {
            return Redirect(string.Format(@"~\Account\LogOn?returnUrl={0}", Request.Url.AbsoluteUri));
         }

         if (!articleID.HasValue)//缺少参数，跳转至错误页面，待修改
         {
            return Redirect(string.Format(@"~\Error.aspx"));
         }

         UserAccount user = UserAccountFactory.GetUserInstanceByCode(User.Identity.Name);

         Apply_Result result = Article.AskForEditing(articleID.Value, user);

         switch (result)
         {
            case Apply_Result.OTHER_USER:
               ViewData["ErrorMessage"] = @"本条目正在被其它用户编辑!";
               ViewData["ReturnURL"] = Request.UrlReferrer.AbsoluteUri;
               return View("ArticleErrors");
            case Apply_Result.WAIT_FOR_APPROVING:
               ViewData["ErrorMessage"] = @"本条目的最新版本正在等待专家审核中！";
               ViewData["ReturnURL"] = Request.UrlReferrer.AbsoluteUri;
               return View("ArticleErrors");
            case Apply_Result.CHECKED_OUT:
            default:
               ViewData["rootCategory"] = KnowledgeEntity.Category.GetAllCategories()[-1];

               Article article = Article.GetArticleById(articleID.Value, Article_Status.EDITING);
               ViewData["CurrentArticle"] = article;
               return View();
         }
      }

      public ActionResult ErrorReturn(string url)
      {
         return Redirect(url);
      }

      public ActionResult CreateArticle()
      {
         ViewData["rootCategory"] = KnowledgeEntity.Category.GetAllCategories()[-1];
         KnowledgeEntity.Article article = new KnowledgeEntity.Article
         {
            ArticleID = -1,
            Title = Request.Form["Title"],
            Content = Request.Form["Content"]
         };

         article = KnowledgeEntity.Article.EditArticle(article);

         return Redirect(string.Format(@"~\Article\ShowArticle\{0}", article.ArticleID));
      }

      public ActionResult ShowArticle(string articleID)
      {
         int parameter = default(int);
         if (!int.TryParse(articleID, out parameter))
         {
            ViewData["ErrorMessage"] = @"缺少文章编号或文章编号不正确!!";
            return new EmptyResult();
         }

         KnowledgeEntity.Article article = KnowledgeEntity.Article.GetArticleById(parameter);

         KnowledgeEntity.Article.AccessArticle(article);

         KnowledgeEntity.Article latestArticle = KnowledgeEntity.Article.GetLatestArticleById(parameter);

         ViewData["article"] = article;
         ViewData["latestArticle"] = latestArticle;

         return View("ShowArticle");
      }

      /// <summary>
      /// 显示待审核的条目
      /// </summary>
      /// <returns></returns>
      public ActionResult ShowWaitingApprove()
      {
         if (!Request.IsAuthenticated)
         {
            return Redirect(string.Format(@"~\Account\LogOn?returnUrl={0}", Request.Url.AbsoluteUri));
         }

         UserAccount user = UserAccountFactory.GetUserInstanceByCode(User.Identity.Name);

         if (!(user is ProfessorAccount))
         {
            return Redirect(string.Format(@"~\Account\LogOn?returnUrl={0}", Request.Url.AbsoluteUri));
         }

         Dictionary<int, Article> articlesToBeApproved = Article.GetArticlesToBeApproved();

         ViewData["ArticlesToBeApproved"] = articlesToBeApproved;

         return View();
      }

      public ActionResult ApproveArticle(int articleID)
      {
         KnowledgeEntity.Article article = KnowledgeEntity.Article.GetArticleById(articleID, Article_Status.WAIT_FOR_APPROVING);

         ViewData["article"] = article;

         return View();
      }

      /// <summary>
      /// 显示单条待审核的条目
      /// </summary>
      /// <param name="articleID"></param>
      /// <returns></returns>
      public ActionResult ShowApprovingArticle(int articleID)
      {
         KnowledgeEntity.Article article = KnowledgeEntity.Article.GetArticleById(articleID, Article_Status.WAIT_FOR_APPROVING);
         ViewData["article"] = article;
         ViewData["latestArticle"] = article;
         return View("ShowArticle");
      }

      [HttpPost]
      [MultiAction(Name="SaveDraft")]
      public ActionResult SaveDraft()
      {
         if (!Request.IsAuthenticated)
         {
            return Redirect(string.Format(@"~\Account\LogOn?returnUrl={0}", Request.UrlReferrer.AbsoluteUri));
         }
         Article article = new Article
         {
            ArticleID = int.Parse(Request.Form["ID"]),
            VersionID = int.Parse(Request.Form["VersionID"]),
            Category = new Category(int.Parse(Request.Form["CategoryID"]), Request.Form["CategoryName"]),
            Content = Request.Form["Content"],
            Title = Request.Form["Title"],
            User = UserAccountFactory.GetUserInstanceByCode(User.Identity.Name)
         };

         ViewData["article"] = KnowledgeEntity.Article.SaveDraft(article);
         ViewData["Draft"] = "draft";
         return View("ShowArticle");
      }

      [HttpPost]
      [MultiAction(Name="Submit")]
      public ActionResult Submit()
      {
         if (!Request.IsAuthenticated)
         {
            return Redirect(string.Format(@"~\Account\LogOn?returnUrl={0}", Request.UrlReferrer.AbsoluteUri));
         }

         Article article = new Article
         {
            ArticleID = int.Parse(Request.Form["ID"]),
            VersionID = int.Parse(Request.Form["VersionID"]),
            Category = new Category(int.Parse(Request.Form["CategoryID"]), Request.Form["CategoryName"]),
            Content = Request.Form["Content"],
            Title = Request.Form["Title"],
            User = UserAccountFactory.GetUserInstanceByCode(User.Identity.Name)
         };

         KnowledgeEntity.Article latestArticle = KnowledgeEntity.Article.Submit(article);
         ViewData["article"] = latestArticle;
         ViewData["latestArticle"] = latestArticle;
         ViewData["submit"] = "submit";
         return View("ShowArticle");
      }

      [HttpPost]
      [MultiAction(Name = "Approve")]
      public ActionResult Approve()
      {
         if (!Request.IsAuthenticated)
         {
            return Redirect(string.Format(@"~\Account\LogOn?returnUrl={0}", Request.UrlReferrer.AbsoluteUri));
         }

         UserAccount user = UserAccountFactory.GetUserInstanceByCode(User.Identity.Name);

         if (!(user is ProfessorAccount))
         {
            return Redirect(string.Format(@"~\Account\LogOn?returnUrl={0}", Request.Url.AbsoluteUri));
         }

         Article article = new Article
         {
            ArticleID = int.Parse(Request.Form["ID"]),
            VersionID = int.Parse(Request.Form["VersionID"])
         };

         (user as ProfessorAccount).Approve(article);

         ViewData["article"] = KnowledgeEntity.Article.GetArticleById(article.ArticleID);
         KnowledgeEntity.Article latestArticle = KnowledgeEntity.Article.GetLatestArticleById(article.ArticleID);

         ViewData["latestArticle"] = latestArticle;
         return View("ShowArticle");
      }

      [HttpPost]
      [MultiAction(Name = "Reject")]
      public ActionResult Reject()
      {
         ViewData["article"] = KnowledgeEntity.Article.GetArticleById(int.Parse(Request.Form["ID"]));
         ViewData["latestArticle"] = KnowledgeEntity.Article.GetLatestArticleById(int.Parse(Request.Form["ID"]));
         return View("ShowArticle");
      }
   }
}
